import { createRouter, RouteRecordRaw, createWebHashHistory } from 'vue-router';

const routerContext = require.context('./modules', true, /\.ts$/) // 获取路由模块的上下文

// 自动引入路由模块
let autoRoute: RouteRecordRaw[] = []
routerContext.keys().forEach(route => {
  const routerModule = routerContext(route) // 得到路由的模块
  // 兼容 import export 和 require module.export 两种规范
  autoRoute = [...autoRoute, ...(routerModule.default || routerModule)]
});

const routes = [
  ...autoRoute,
  {
    path: "/",
    redirect: "/home"
  },
  { path: '/home', component: () => import('@/pages/homePage/HomePage.vue') },
  {
    path: '/login',
    name: 'login',
    meta: {
      index: 1,
      title: '登录'
    },
    component: () => import('@/pages/login/loginPage.vue')
  },
  {
    path: '/register',
    name: 'register',
    meta: {
      index: 2,
      title: '注册'
    },
    component: () => import('@/pages/register/registerPage.vue')
  },

];
// 创建router实例
const router = createRouter({
  // history: createWebHistory(),
  history: createWebHashHistory(),
  routes,
})

export type RouteConfigs = RouteRecordRaw[];
// 模拟从后端获取动态路由数据的函数
export async function fetchDynamicRoutes(): Promise<RouteConfigs> {
  // 这里应该是实际的 API 调用，返回符合 RouteRecordRaw 结构的数组
  return [
  ];
}
// 动态添加路由的函数
export async function addDynamicRoutes() {
  const dynamicRoutes = await fetchDynamicRoutes();
  dynamicRoutes.forEach((route) => {
    router.addRoute(route);
  });
}


// 添加路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem("isLoggedIn")
  if (to.meta.requiresAuth && !isLoggedIn) {
    // 如果要访问的路由需要认证，且用户未登录，则重定向到登录页面
    next('/login');
  } else {
    // 否则允许访问
    next()
  }
})
export default router